package com.projectsexception.festivales.news.view;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.projectsexception.festivales.R;
import com.projectsexception.festivales.news.model.Feed;
import com.projectsexception.festivales.news.model.FeedEntry;
import com.projectsexception.festivales.util.DateFormater;

public class FeedEntryAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private Feed feed;

    public FeedEntryAdapter(Context context, Feed feed) {
        inflater = LayoutInflater.from(context);
        this.feed = feed;

    }

    public int getCount() {
        return feed.getEntryList().size();
    }

    public Object getItem(int position) {
        return feed.getEntryList().get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View entryView, ViewGroup parent) {
        if (entryView == null) {
            entryView = inflater.inflate(R.layout.tab_news_feed_entry, null);
        }
        
        FeedEntry entry = feed.getEntryList().get(position);
        TextView textView = (TextView) entryView.findViewById(R.id.entry_title);
        textView.setText(entry.getTitle());
        textView = (TextView) entryView.findViewById(R.id.entry_date);
        textView.setText(formatPubdate(entry.getPubdate()));

        return entryView;
    }
    
    private String formatPubdate(String pubdate) {
        Date date = DateFormater.parseFeedDate(pubdate);
        if (date != null) {
            String datePattern = "HH:mm";
            Calendar calendarDate = GregorianCalendar.getInstance();
            Calendar calendarToday = GregorianCalendar.getInstance();
            calendarDate.setTime(date);
            calendarToday.setTime(new Date());
            if (calendarDate.get(Calendar.YEAR) != calendarToday.get(Calendar.YEAR)
                    || calendarDate.get(Calendar.MONTH) != calendarToday.get(Calendar.MONTH)
                    || calendarDate.get(Calendar.DAY_OF_MONTH) != calendarToday.get(Calendar.DAY_OF_MONTH)) {
                if (calendarDate.get(Calendar.HOUR_OF_DAY) == 0 && calendarDate.get(Calendar.MINUTE) == 0) {
                    datePattern = "dd/MM/yyyy";
                } else {
                    datePattern = "dd/MM/yyyy " + datePattern;
                }
            }
            return new SimpleDateFormat(datePattern).format(date);
        } else {
            return pubdate;
        }
        
    }

}
